<?php

namespace App\Service\Admin;

use App\Model\Admin\AdminModel;
use App\Service\BaseService;
use http\Exception;

/**
 * 后台用户管理-服务类
 * @author LZH
 * @since: 2021/08/12
 * Class AdminService
 */
class AdminService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new AdminModel();
        parent::__construct();
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2021/08/12
     * @author LZH
     */
    public function getList()
    {
        $this->log_info('获取管理人员列表信息');
        $param = $this->getRequestParam();

        // 查询条件
        $map = [];


        return parent::getList($map);
    }

    /**
     * 添加或编辑
     */
    public function edit()
    {
        $data = $this->getRequestParam();

        if (strpos($data['avatar'], "temp")) { // 对于保存用户，需要把图片从临时文件转储到正式文件目录
            $data['avatar'] = save_image($data['avatar'], 'user');
        } else { // 对于编辑用户，需要把图片路径中域名部门去掉
            $data['avatar'] = str_replace(IMG_URL, "", $data['avatar']);
        }

        // 添加时设置密码
        if (empty($data['id'])) {
            $username = trim($data['username']);
            $password = trim($data['password']);
            $data['password'] = password_hash($password . $username, PASSWORD_BCRYPT);
        }

        try {
            $this->model->startTrans();

            $result = $this->model->edit($data);
            // 删除已存在的用户角色关系数据
            $userRoleService = new UserRoleService();
            $userRoleService->deleteUserRole($result);
            // 插入用户角色关系数据
            $userRoleService->insertUserRole($result, $data['role_ids']);

            if ($this->model->commit()) {
                return $result;
            }
            return false;
        } catch (\Throwable $exception) {
            $this->model->rollback();
            $this->exception_error($exception);
            throw $exception;
        }
    }

    /**
     * 获取指定用户的详情
     * @param $userId
     * @return \App\Model\数据信息|mixed
     * @author LZH
     */
    public function getUserInfo($userId)
    {
        $userInfo = $this->model->getInfoById($userId);
        $userInfo['roles'] = [];
        $userInfo['authorities'] = [];
        return $userInfo;
    }

    /**
     * 重置密码
     * @return mixed
     * @author LZH
     */
    public function resetPwd()
    {
        // 获取参数 用户ID
        $userId = $this->getRequestParam('id');

        $userInfo = $this->model->getInfoById($userId);

        $item = [
            'id' => $userId,
            'password' => password_hash("123456" . $userInfo['username'], PASSWORD_BCRYPT),
        ];
        return $this->model->edit($item);
    }
}
